<template>
  <view class="container">
    <!-- 顶部调音指示器 -->
    <view class="tuning-meter">
      <text class="center-value">0</text>
      <view class="center-line"></view>
      <view class="scale-marks">
        <view class="mark-line" v-for="i in 30" :key="i"></view>
      </view>
      <view class="scale-labels">
        <text class="scale-label">低</text>
        <text class="scale-label">高</text>
      </view>
    </view>
    
    <!-- 吉他琴头区域 -->
    <view class="guitar-area">
      <view class="guitar-head-wrapper">
        <!-- SVG琴头 -->
        <svg class="guitar-head" viewBox="0 0 300 800" xmlns="http://www.w3.org/2000/svg">
          <!-- 琴头轮廓 -->
          <path class="headstock-outline" d="M150,100 L90,150 L90,700 L210,700 L210,150 Z" fill="none" stroke="rgba(255,255,255,0.5)" stroke-width="2" />
          
          <!-- 琴弦 -->
          <line class="guitar-string" x1="105" y1="700" x2="105" y2="120" stroke="#7FDBFF" stroke-width="2" />
          <line class="guitar-string" x1="125" y1="700" x2="125" y2="120" stroke="rgba(255,255,255,0.3)" stroke-width="1.5" />
          <line class="guitar-string" x1="145" y1="700" x2="145" y2="120" stroke="rgba(255,255,255,0.3)" stroke-width="1.5" />
          <line class="guitar-string" x1="165" y1="700" x2="165" y2="120" stroke="rgba(255,255,255,0.3)" stroke-width="1.5" />
          <line class="guitar-string" x1="185" y1="700" x2="185" y2="120" stroke="rgba(255,255,255,0.3)" stroke-width="1.5" />
          <line class="guitar-string" x1="195" y1="700" x2="195" y2="120" stroke="rgba(255,255,255,0.3)" stroke-width="1.5" />
          
          <!-- 琴弦标记 -->
          <text x="150" y="730" text-anchor="middle" class="string-numbers" fill="rgba(255,255,255,0.7)">6 5 4 3 2 1</text>
          
          <!-- 旋钮 -->
          <circle class="tuning-peg" cx="105" cy="140" r="12" fill="rgba(80,80,100,0.5)" stroke="rgba(255,255,255,0.4)" stroke-width="1" />
          <circle class="tuning-peg" cx="125" cy="140" r="12" fill="rgba(80,80,100,0.5)" stroke="rgba(255,255,255,0.4)" stroke-width="1" />
          <circle class="tuning-peg" cx="145" cy="140" r="12" fill="rgba(80,80,100,0.5)" stroke="rgba(255,255,255,0.4)" stroke-width="1" />
          <circle class="tuning-peg" cx="165" cy="140" r="12" fill="rgba(80,80,100,0.5)" stroke="rgba(255,255,255,0.4)" stroke-width="1" />
          <circle class="tuning-peg" cx="185" cy="140" r="12" fill="rgba(80,80,100,0.5)" stroke="rgba(255,255,255,0.4)" stroke-width="1" />
          <circle class="tuning-peg" cx="195" cy="140" r="12" fill="rgba(80,80,100,0.5)" stroke="rgba(255,255,255,0.4)" stroke-width="1" />
        </svg>
        
        <!-- 音符气泡 -->
        <view class="note-bubbles">
          <!-- 左侧音符 -->
          <view class="note-bubble left" :class="{ active: selectedString === 0 }" @tap="selectString(0)">
            <text>D</text>
          </view>
          <view class="note-bubble left" :class="{ active: selectedString === 2 }" @tap="selectString(2)">
            <text>A</text>
          </view>
          <view class="note-bubble left" :class="{ active: selectedString === 4 }" @tap="selectString(4)">
            <text>E</text>
          </view>
          
          <!-- 右侧音符 -->
          <view class="note-bubble right" :class="{ active: selectedString === 1 }" @tap="selectString(1)">
            <text>G</text>
          </view>
          <view class="note-bubble right" :class="{ active: selectedString === 3 }" @tap="selectString(3)">
            <text>B</text>
          </view>
          <view class="note-bubble right" :class="{ active: selectedString === 5 }" @tap="selectString(5)">
            <text>E</text>
          </view>
        </view>
        
        <!-- 当前检测到的音符 -->
        <view class="detected-note-circle" :style="{ backgroundColor: getTuningColor() }">
          <text>{{ currentNote[0] }}</text>
        </view>
      </view>
    </view>
    
    <!-- 大音符显示 -->
    <view class="note-display">
      <text class="note-name" :style="{ color: getTuningColor() }">{{ currentNote }}</text>
      <text class="frequency">{{ currentFrequency }} Hz</text>
      
      <!-- 调音指示器 -->
      <view class="tuning-indicator">
        <view class="indicator-bar"></view>
        <view 
          class="indicator-needle"
          :style="{ 
            left: `${50 + tuningOffset}%`,
            backgroundColor: getTuningColor()
          }"
        ></view>
      </view>
      <text class="tuning-status" :style="{ color: getTuningColor() }">
        {{ getTuningStatus() }} ({{ displayError }})
      </text>
    </view>
    
    <!-- 底部控制区 -->
    <view class="manual-control">
      <text>手动</text>
      <view class="switch-control"></view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import themeService from '../../utils/themeService.js';

// 状态
const isListening = ref(true);
const currentNote = ref('D3');
const currentFrequency = ref(146.83);
const tuningOffset = ref(0); // -50到50的范围，0表示调准了
const selectedString = ref(0);
const autoTuning = ref(false);
const standardAFrequency = ref(440); // 标准A4音频率，可调整
const frequencyError = ref(0); // 与标准音的差值(Hz)

// 计算属性
const displayError = computed(() => {
  if (frequencyError.value === 0) return '0 Hz';
  const sign = frequencyError.value > 0 ? '+' : '';
  return `${sign}${frequencyError.value.toFixed(2)} Hz`;
});

// 动态计算当前所选琴弦的理想频率
const currentTargetFrequency = computed(() => {
  if (!guitarStrings[selectedString.value]) return 0;
  
  // 根据标准A4频率调整其他音符频率
  const baseFreq = guitarStrings[selectedString.value].frequency;
  const standardRatio = standardAFrequency.value / 440;
  
  return baseFreq * standardRatio;
});

// 吉他弦定义 - 顺序与图中布局一致
const guitarStrings = [
  { note: 'D3', frequency: 146.83, string: '4弦' },
  { note: 'G3', frequency: 196.00, string: '3弦' },
  { note: 'A2', frequency: 110.00, string: '5弦' },
  { note: 'B3', frequency: 246.94, string: '2弦' },
  { note: 'E2', frequency: 82.41, string: '6弦' },
  { note: 'E4', frequency: 329.63, string: '1弦' }
];

function selectString(index) {
  selectedString.value = index;
  resetTuner();
  
  // 自动开始调音
  if (!isListening.value) {
    startTuner();
  }
}

function resetTuner() {
  currentNote.value = guitarStrings[selectedString.value].note;
  currentFrequency.value = 0;
  tuningOffset.value = 0;
  frequencyError.value = 0;
}

function startTuner() {
  isListening.value = true;
  simulateTuner();
}

function stopTuner() {
  isListening.value = false;
  clearInterval(simulationInterval);
}

let simulationInterval;

function simulateTuner() {
  // 清除之前的模拟
  clearInterval(simulationInterval);
  
  // 开始模拟频率检测
  simulationInterval = setInterval(() => {
    const targetFreq = currentTargetFrequency.value;
    
    // 如果开启了自动调整且上次检测的频率不为0
    if (autoTuning.value && currentFrequency.value > 0) {
      // 逐渐向目标频率靠近
      const adjustmentStep = 0.5;
      const currentDiff = targetFreq - currentFrequency.value;
      
      let newVariation = 0;
      if (Math.abs(currentDiff) > adjustmentStep) {
        newVariation = currentDiff > 0 ? adjustmentStep : -adjustmentStep;
      } else {
        newVariation = currentDiff;
      }
      
      currentFrequency.value = Math.round((currentFrequency.value + newVariation) * 100) / 100;
    } else {
      // 普通模式：随机偏差
      const variation = Math.random() * 20 - 10; // -10到10的随机变化
      currentFrequency.value = Math.round((targetFreq + variation) * 100) / 100;
    }
    
    // 计算与目标频率的差值
    frequencyError.value = Math.round((currentFrequency.value - targetFreq) * 100) / 100;
    
    // 计算相对偏移量用于显示
    tuningOffset.value = Math.round(frequencyError.value / targetFreq * 100);
    
    // 确保tuningOffset在-50到50的范围内
    tuningOffset.value = Math.max(-50, Math.min(50, tuningOffset.value));
    
    // 更新当前音符
    currentNote.value = guitarStrings[selectedString.value].note;
  }, 500);
}

function getTuningStatus() {
  const offset = Math.abs(tuningOffset.value);
  
  if (offset < 5) {
    return '已调准';
  } else if (offset < 15) {
    return '接近调准';
  } else if (tuningOffset.value > 0) {
    return '音调过高';
  } else {
    return '音调过低';
  }
}

function getTuningColor() {
  const offset = Math.abs(tuningOffset.value);
  
  if (offset < 5) {
    return '#4CAF50'; // 绿色
  } else if (offset < 15) {
    return '#FFC107'; // 黄色
  } else {
    return '#F44336'; // 红色
  }
}

// 生命周期钩子
onLoad(() => {
  // 自动开始调音
  startTuner();
});

onUnmounted(() => {
  // 清理资源
  if (isListening.value) {
    stopTuner();
  }
});
</script>

<style>
.container {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100vh;
  box-sizing: border-box;
  background-color: #121026;
  color: #FFFFFF;
  position: relative;
}

/* 顶部调音指示器 */
.tuning-meter {
  padding: 30rpx 0;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.center-value {
  position: absolute;
  top: 10rpx;
  font-size: 32rpx;
  color: #7FDBFF;
  z-index: 2;
}

.center-line {
  position: absolute;
  top: 60rpx;
  width: 2rpx;
  height: 80rpx;
  background-color: #7FDBFF;
  z-index: 2;
}

.scale-marks {
  width: 100%;
  height: 40rpx;
  display: flex;
  justify-content: space-between;
  padding: 0 60rpx;
  margin-top: 50rpx;
  box-sizing: border-box;
}

.mark-line {
  width: 1px;
  height: 16rpx;
  background-color: rgba(255, 255, 255, 0.3);
}

.mark-line:nth-child(5n+1) {
  height: 24rpx;
}

.scale-labels {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 0 60rpx;
  box-sizing: border-box;
}

.scale-label {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.6);
}

/* 吉他琴头区域 */
.guitar-area {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
}

.guitar-head-wrapper {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
}

.guitar-head {
  width: 100%;
  height: 90%;
  max-width: 600rpx;
}

.headstock-outline {
  opacity: 0.8;
}

.guitar-string {
  opacity: 0.8;
}

.string-numbers {
  font-size: 24rpx;
  letter-spacing: 26rpx;
}

/* 音符气泡 */
.note-bubbles {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

.note-bubble {
  position: absolute;
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.3s;
}

.note-bubble.left {
  left: 15%;
}

.note-bubble.right {
  right: 15%;
}

.note-bubble:nth-child(1), .note-bubble:nth-child(4) {
  top: 20%;
}

.note-bubble:nth-child(2), .note-bubble:nth-child(5) {
  top: 45%;
}

.note-bubble:nth-child(3), .note-bubble:nth-child(6) {
  top: 70%;
}

.note-bubble.active {
  background-color: #7FDBFF;
  border-color: #7FDBFF;
  box-shadow: 0 0 20rpx rgba(127, 219, 255, 0.8);
}

.note-bubble text {
  font-size: 36rpx;
  font-weight: bold;
  color: white;
}

.detected-note-circle {
  position: absolute;
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  background-color: #4CAF50;
  display: flex;
  justify-content: center;
  align-items: center;
  bottom: 30%;
  left: 50%;
  transform: translateX(-50%);
  box-shadow: 0 0 30rpx rgba(76, 175, 80, 0.5);
  z-index: 10;
}

.detected-note-circle text {
  font-size: 60rpx;
  font-weight: bold;
  color: white;
}

/* 音符显示区域 */
.note-display {
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.note-name {
  font-size: 120rpx;
  font-weight: bold;
  color: #4CAF50;
  line-height: 1;
}

.frequency {
  font-size: 28rpx;
  color: #B0BEC5;
  margin: 10rpx 0 30rpx;
}

.tuning-indicator {
  width: 80%;
  height: 6rpx;
  background-color: rgba(255,255,255,0.1);
  position: relative;
  margin-bottom: 20rpx;
}

.indicator-bar {
  width: 100%;
  height: 100%;
  background-color: rgba(255,255,255,0.1);
  border-radius: 3rpx;
}

.indicator-needle {
  position: absolute;
  width: 4rpx;
  height: 40rpx;
  background-color: #4CAF50;
  border-radius: 2rpx;
  top: -17rpx;
  transform: translateX(-50%);
  transition: all 0.3s ease;
}

.tuning-status {
  font-size: 28rpx;
  font-weight: bold;
  margin-top: 10rpx;
}

/* 底部控制 */
.manual-control {
  padding: 20rpx;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20rpx;
}

.manual-control text {
  font-size: 28rpx;
  color: #B0BEC5;
  margin-right: 20rpx;
}

.switch-control {
  width: 100rpx;
  height: 50rpx;
  background-color: rgba(76, 175, 80, 0.3);
  border-radius: 25rpx;
  position: relative;
}

.switch-control::after {
  content: '';
  position: absolute;
  right: 5rpx;
  top: 5rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #4CAF50;
  transition: all 0.3s;
}
</style> 